package com.bw.shop2208a.mvvm

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.Objects
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean

class SingleLiveData<T> : MutableLiveData<T>() {
    var map: ConcurrentHashMap<Any, AtomicBoolean> = ConcurrentHashMap()

    private val atomicBoolean1 = AtomicBoolean()

    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, observer)
        val observer1 = Observer<T> {
            val atomicBoolean = map[observer]
            if (atomicBoolean != null) {
                if (atomicBoolean.compareAndSet(true, false)) {
                    atomicBoolean.set(false);
                }
            }
        }
        map[observer1] = AtomicBoolean()
    }

    override fun setValue(value: T) {
        super.setValue(value)
        for (value in map.values) {
            value.set(true)
        }
    }
}